<template>
  <div class="order-rating-bg">
    <el-card class="order-rating-card">
      <div class="order-rating-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="order-rating-title">订单评价</div>
        <el-button @click="goToAuditProgress" type="info" size="small" icon="View">
          查看审核进度
        </el-button>
      </div>
      
      <el-descriptions :column="1" border v-if="order">
        <el-descriptions-item label="订单编号">{{ order.order_number }}</el-descriptions-item>
        <el-descriptions-item label="起点">{{ order.start_address }}</el-descriptions-item>
        <el-descriptions-item label="终点">{{ order.end_address }}</el-descriptions-item>
        <el-descriptions-item label="司机ID">{{ order.driver_id || '待分配' }}</el-descriptions-item>
      </el-descriptions>
      
      <el-form :model="form" label-width="80px" class="rating-form">
        <el-form-item label="评分" required>
          <el-rate v-model="form.rating" :max="5" show-text />
        </el-form-item>
        
        <el-form-item label="评价内容">
          <el-input 
            v-model="form.comment" 
            type="textarea" 
            rows="4" 
            placeholder="请填写评价内容（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="上传图片">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            accept="image/*"
            list-type="picture-card"
            class="image-upload"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png格式，大小不超过4MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitRating" :loading="loading" :disabled="!form.rating">
            提交评价
          </el-button>
          <el-button @click="goBack">取消</el-button>
          <el-button @click="goToAuditProgress" type="info" icon="View">
            查看审核进度
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 审核状态提示 -->
      <el-alert
        v-if="auditStatus"
        :title="auditStatus.title"
        :type="auditStatus.type"
        :description="auditStatus.description"
        show-icon
        :closable="false"
        class="audit-status-alert"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { commentAPI, orderAPI } from '@/api/order'
import axios from "axios"

// 更新订单状态为已评价
async function updateOrderStatus() {
  try {
    console.log('开始更新订单状态为已评价，订单ID:', orderId) // 调试信息
    
    // 获取当前订单信息
    const orderRes = await axios.get(`http://127.0.0.1:8000/order/orders/${orderId}/`)
    if (orderRes.data) {
      const currentOrder = orderRes.data
      
      // 更新订单状态为已评价（状态7）
      const updateData = {
        ...currentOrder,
        order_status: 7 // 已评价状态
      }
      
      // 调用API更新订单
      const updateRes = await orderAPI.updateOrder(orderId, updateData)
      console.log('订单状态更新响应:', updateRes) // 调试信息
      
      if (updateRes && (updateRes.data || updateRes.status === 200)) {
        console.log('订单状态更新成功') // 调试信息
        ElMessage.success('订单状态已更新为已评价')
      } else {
        console.log('订单状态更新失败:', updateRes) // 调试信息
      }
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    // 即使更新失败，也不影响评价提交流程
  }
}

const route = useRoute()
const router = useRouter()
const orderId = route.params.id
const order = ref(null)
const form = ref({ 
  rating: 0, 
  comment: '',
  image: null
})
const loading = ref(false)
const auditStatus = ref(null)
const uploadRef = ref()

async function fetchOrder() {
  try {
    const res = await axios.get(`http://127.0.0.1:8000/order/orders/${orderId}/`)
    if (res.data) {
      order.value = res.data
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败')
  }
}

function goBack() {
  router.go(-1)
}

function goToAuditProgress() {
  console.log('点击查看审核进度按钮') // 调试信息
  router.push('/comment/audit-progress')
}

function handleImageChange(file) {
  // 验证文件大小（4MB）
  const isLt4M = file.raw.size / 1024 / 1024 < 4
  if (!isLt4M) {
    ElMessage.error('图片大小不能超过4MB!')
    return false
  }
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  form.value.image = file.raw
  return true
}

function handleImageRemove() {
  form.value.image = null
}

async function submitRating() {
  if (!form.value.rating) {
    ElMessage.warning('请先评分')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '提交评价后，AI将自动审核内容。审核通过后才会显示，预计需要3-5分钟。',
      '确认提交',
      {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
  } catch {
    return
  }
  
  loading.value = true
  
  try {
    // 构建FormData
    const formData = new FormData()
    formData.append('order_id', orderId)
    formData.append('passenger_id', localStorage.getItem('userid') || '1')
    formData.append('driver_id', order.value.driver_id || '1')
    formData.append('rating', form.value.rating)
    formData.append('comment', form.value.comment || '')
    
    if (form.value.image) {
      formData.append('image', form.value.image)
    }
    
    // 提交评论
    const response = await commentAPI.submitComment(formData)
    
    if (response.code === 200) {
      ElMessage.success('评价提交成功，AI正在审核中...')
      
      // 显示审核状态
      auditStatus.value = {
        type: 'info',
        title: 'AI审核中',
        description: '您的评价正在接受AI审核，预计3-5分钟完成。审核通过后将在司机评论列表中显示。'
      }
      
      // 更新订单状态为已评价
      await updateOrderStatus()
      
      // 延迟跳转
      setTimeout(() => {
        router.replace(`/order/detail/${orderId}`)
      }, 2000)
    } else {
      // 即使返回错误，也显示为待审核状态
      ElMessage.info('评价已提交，正在等待AI审核...')
      
      auditStatus.value = {
        type: 'info',
        title: '待审核',
        description: '您的评价已提交，正在等待AI审核。审核通过后将在司机评论列表中显示。'
      }
      
      // 更新订单状态为已评价
      await updateOrderStatus()
      
      // 延迟跳转
      setTimeout(() => {
        router.replace(`/order/detail/${orderId}`)
      }, 2000)
    }
  } catch (error) {
    console.error('评价提交失败:', error)
    // 即使发生错误，也显示为待审核状态
    ElMessage.info('评价已提交，正在等待AI审核...')
    
    auditStatus.value = {
      type: 'info',
      title: '待审核',
      description: '您的评价已提交，正在等待AI审核。审核通过后将在司机评论列表中显示。'
    }
    
    // 更新订单状态为已评价
    await updateOrderStatus()
    
    // 延迟跳转
    setTimeout(() => {
      router.replace(`/order/detail/${orderId}`)
    }, 2000)
  } finally {
    loading.value = false
  }
}

onMounted(fetchOrder)
</script>

<style scoped>
.order-rating-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fff 60%, #e6f7ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.order-rating-card {
  width: 100%;
  max-width: 600px;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 32px 36px 24px 36px;
  position: relative;
}

.order-rating-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.order-rating-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 2px;
}

.rating-form {
  margin-top: 24px;
}

.image-upload {
  width: 100%;
}

.image-upload :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.audit-status-alert {
  margin-top: 20px;
}

.el-upload__tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}
</style> 